package com.dog.view.converter;

import com.dog.model.Customer;
import com.dog.service.ICustomerService;
import com.dog.spring.ServiceFactory;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

/**
 * User: Kuttubek Aidaraliev
 * Date: 07.05.2010
 * Time: 7:30:18
 */
public class OrganizationConverter implements Converter {


    @Override
    public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String s) {
        ICustomerService customerService = ServiceFactory.getCustomerService();
        System.out.println(customerService + " " + s);
        Customer customer = null;
        try {
            customer = customerService.get(new Long(s));
        } catch (Exception e){
            FacesMessage facesMessage = new FacesMessage("Conversation error occurred. ",
                    "Invalid Organization selected. ");
            facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ConverterException(facesMessage);
        }
        if(customer == null){
            FacesMessage facesMessage = new FacesMessage("Conversation error occurred. ",
                        "Organization not found. ");
            facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ConverterException(facesMessage);
        }

        return customer;
    }

    @Override
    public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object o) {
         if(o instanceof Customer) {
            Customer customer = (Customer)o;
            return customer.getId().toString();
        }
        else throw new IllegalArgumentException("Argument must be Customer object!");
    }
}
